package com.demo.interrupted;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.*;

@Configuration
@Component
public class ConfigrationClass implements InitializingBean {

    @Bean(value = "threadPool")
    public ExecutorService getThreadPoolExcutor(){
        ExecutorService executorService =
                new ThreadPoolExecutor(3,
                        3,
                        60L, TimeUnit.SECONDS,
                        new SynchronousQueue<Runnable>(),
                        new ThreadFactory(){

                            @Override
                            public Thread newThread(Runnable r) {
                                Thread t = new Thread(r);
//                                t.setDaemon(true);
                                return t;
                            }
                        }, new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        try {
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            Thread.currentThread().interrupt();
                        }
                    }
                });
        return executorService;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000000; i++) {
                    try {
                        TaskQueueHolder.get().put(i + "");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.currentThread().sleep(888);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.setName("Thread-task-creator-mode");
        t.setDaemon(true);
        t.start();
    }
}

